package com.knife.news.manage.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.knife.news.logic.GrabService;
import com.knife.news.logic.impl.GrabServiceImpl;
import com.knife.news.object.Logs;
import com.knife.news.object.Grab;
import com.knife.tools.Similarity;
import com.knife.util.CommUtil;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class GrabManageAjaxAction extends ManageAction {
	private GrabService grabDAO = GrabServiceImpl.getInstance();
	
	public Page doAdd(WebForm form,Module module){
		com.knife.news.model.Grab grab = (com.knife.news.model.Grab) form.toPo(com.knife.news.model.Grab.class);
		Grab agrab=new Grab(grab);
		String retid=grabDAO.saveGrab(agrab);
		if (!"".equals(retid)) {
			//记录日志
			Logs log=new Logs(user.getUsername()+"添加采集:"+grab.getTitle());
			logDAO.saveLogs(log);
			form.addResult("jvalue", retid);
		} else {
			form.addResult("jvalue", "0");
		}
		return module.findPage("ajax");
	}
	
	//添加列表特征码
//	public Page doAddListDna(WebForm form,Module module){
//		String id = CommUtil.null2String(form.get("id"));
//		String list_dna = CommUtil.null2String(form.get("list_dna"));
//		Grab agrab=grabDAO.getGrabById(id);
//		Document dom = Jsoup.parse(list_dna);
//		Elements links = dom.getElementsByTag("a");
//		Elements childrens;
//		if(links!=null){
//			for(Element link : links){
//				childrens = link.children();
//				link.attr("href", "");
//				link.html("");
//				if(childrens != null){
//					for(Element child : childrens){
//						child.html("");
//					}
//				}
//			}
//		}		
//		Elements lis = dom.getElementsByTag("li");
//		Elements childs;
//		if(lis!=null){
//			for(Element li : lis){
//				 childs = li.children();
//				if( childs != null){
//					for(Element child :  childs){
//						child.html("");
//					}
//				}
//			}
//		}		
//		String dnaText = dom.outerHtml().replaceAll("<html>", "");
//		dnaText = dnaText.replaceAll("</html", "");
//		dnaText = dnaText.replaceAll("<head>", "");
//		dnaText = dnaText.replaceAll("</head>", "");
//		dnaText = dnaText.replaceAll("<body>", "");
//		dnaText = dnaText.replaceAll("</body>", "");
//		agrab.setList_dna(dnaText);
//		try{
//			grabDAO.updateGrab(agrab);
//			form.addResult("jvalue", "更新list_dna完成");
//		}catch (Exception e) {
//			form.addResult("jvalue", "更新list_dna失败");
//		}
//		return module.findPage("ajax");
//	}
	
	public Page doAddListDna(WebForm form,Module module){
		Document domAll = null;
		String id;
//		String domAllText;
		String listdna_head;
		String listdna_foot;
		String url;
		String content;
		String pageHtml;
		String list_dna;
		String sbHead = "";
		String sbFoot = "";
		Element body;
		
		id = CommUtil.null2String(form.get("id"));
		list_dna = CommUtil.null2String(form.get("list_dna"));
		pageHtml = CommUtil.null2String(form.get("pageHtml"));
		Grab agrab=grabDAO.getGrabById(id);
//		Document domList = Jsoup.parse(list_dna);
		
		listdna_head = pageHtml.substring(0,pageHtml.indexOf(list_dna));
		listdna_foot = pageHtml.substring(pageHtml.indexOf(list_dna)+list_dna.length(),pageHtml.length());
		
		int lastIndex = listdna_head.lastIndexOf("class=\"selected_list\"");
		if( lastIndex < 0 ){
			lastIndex = listdna_head.lastIndexOf("class=selected_list");
		}
		String last = listdna_head.substring(lastIndex-200,listdna_head.length());
		int lastT = last.indexOf("<ul");
		if(lastT<0){
			lastT = last.indexOf("<UL");
		}
		last = last.replaceAll(last.substring(lastT,last.length()),"");
		listdna_head = listdna_head.replaceAll(listdna_head.substring(lastIndex-200,listdna_head.length()), last);
		
		
		if(agrab.getListdna_head()!=null){
			url = agrab.getUrl2();
		}else{
			url = agrab.getUrl();
		}
		try {
			domAll = Jsoup.connect(url).get();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("不能链接到目标站点！请稍后重试");
		}
		
//		domListText = domList.outerHtml().replaceAll("<html>", "");
//		domListText = domListText.replaceAll("</html", "");
//		domListText = domListText.replaceAll("<head>", "");
//		domListText = domListText.replaceAll("</head>", "");
//		domListText = domListText.replaceAll("<body>", "");
//		domListText = domListText.replaceAll("</body>", "");
//		String subDomListText =  domListText.substring(domListText.indexOf("<ul")+4,domListText.indexOf("<ul")+100);
//		domAllText = domAll.outerHtml();
//		
//		System.out.println("文档页面内容为:\n" + domAllText);
//		System.out.println("domListText内容为:\n" + domListText.substring(domListText.indexOf("<ul")+4,domListText.indexOf("<ul")+100));
//		System.out.println("domListText在全文的索引位置为:\n" + domAllText.indexOf(domListText.substring(domListText.indexOf("<ul")+4,domListText.indexOf("<ul")+100).replaceAll("\"","\\"+"\"").trim()));
//		
//		listdna_head = domAllText.substring(0,domAllText.indexOf(subDomListText));
//		listdna_foot = domAllText.substring(domAllText.indexOf(domListText)+domAllText.length());
		
		if(agrab.getListdna_head()==null){
			agrab.setListdna_head(listdna_head);
			agrab.setListdna_foot(listdna_foot);
			try{
				grabDAO.updateGrab(agrab);
				body = domAll.select("body").first();
				body.append("<input type=\"hidden\" id=\"grabid\" value=" + id + " name=\"grabid\"/>");
				Elements uls = domAll.getElementsByTag("ul");
				Elements ols = domAll.getElementsByTag("ol");
				if(uls!=null){
					for(Element ul : uls){
						ul.attr("class", "selected_list");
					}
				}
				if(ols!=null){
					for(Element ol : ols){
						ol.attr("class", "selected_list");
					}
				}
				Elements bases = domAll.getElementsByTag("base");
				if(bases!=null){
					Element base = bases.first();
					base.html("");
				}
				Element head = domAll.getElementsByTag("head").first();
				head.append("<script language='javascript' src='/include/manage/js/jquery.js'></script>");
				head.append("<script language='javascript' src='/include/manage/js/grab.js'></script>");
				head.append("<link rel='stylesheet' href='/include/manage/js/grab_list.css' type='text/css' media='screen' />");
				content= domAll.outerHtml();
//				StringBuffer sbscript=new StringBuffer("\n<script language=\"javascript\" src=\"/include/manage/js/jquery.js\"></script>\n");
//				sbscript.append("\n<script language=\"javascript\" src=\"/include/manage/js/grab.js\"></script>\n");
//				sbscript.append("\n<link rel=\"stylesheet\" href=\"/include/manage/js/grab_list.css\" type=\"text/css\" media=\"screen\" />\n ");
//				content+=sbscript.toString();
				if( domAll!=null){
					form.addResult("content", content);
				}
				form.addResult("jvalue", content);
			}catch (Exception e) {
				form.addResult("jvalue", "链接到第二页面失败");
			}
			return module.findPage("ajax");
		}else{
			String head = agrab.getListdna_head();
			String foot = agrab.getListdna_foot();
//			List<String> heads = new ArrayList<String>();
//			List<String> foots = new ArrayList<String>();
//			StringBuffer sbHead = new StringBuffer();
//			StringBuffer sbFoot = new StringBuffer();
			head = head.substring(head.length()-200);
			foot = foot.substring(0, 200);
			listdna_head = listdna_head.substring(listdna_head.length()-200);
			listdna_foot = listdna_foot.substring(0, 200);
			flag : for(int i = head.length() ; i > 0 ; i--){
							for(int j = listdna_head.length() ; j > 0 ; j--){
								if(i==j){
//									if(head.substring(head.indexOf(i-1),head.indexOf(i-1)+1).equals(listdna_head.substring(listdna_head.indexOf(j-1),listdna_head.indexOf(j-1)+1))){
//										heads.add(head.substring(head.indexOf(i-1),head.indexOf(i-1)+1));
//									}else{
									if(head.substring(i-1).equals(listdna_head.substring(j-1))){
//										heads.add(head.substring(i-1));
										sbHead = head.substring(i-1);
									}else{
										break flag;
									}
								}
							}
						}
			z :		 for(int i = 0 ; i < foot.length() ; i++){
							for(int j = 0 ; j < listdna_foot.length() ; j++){
								if(i==j){
//									if(foot.substring(foot.indexOf(i),foot.indexOf(i)+1).equals(listdna_foot.substring(listdna_foot.indexOf(j),listdna_foot.indexOf(j)+1))){
//										foots.add(foot.substring(foot.indexOf(i),foot.indexOf(i)+1));
//									}else{
									if(foot.substring(i).equals(listdna_foot.substring(j))){
//										foots.add(foot.substring(i));
										sbFoot = foot.substring(0,i);
									}else{
										break z;
									}
								}
							}
						}
						
//			for(int i = heads.size() ; i > 0 ; i--){
//				sbHead.append(heads.get(i));
//			}
//			for(int i = 0 ; i < foots.size() ; i++){
//				sbHead.append(foots.get(i));
//			}
//			sbHead = heads.get(heads.size()-1);
//			sbFoot = foots.get(foots.size()-1);
			agrab.setListdna_head(sbHead);
			agrab.setListdna_foot(sbFoot);
			
			try{
				grabDAO.updateGrab(agrab);
				form.addResult("jvalue", "更新list_dna完成");
			}catch (Exception e) {
				form.addResult("jvalue", "更新list_dna失败");
			}
			return module.findPage("ajax");
		}
	}
	
	public Page doShowList(WebForm form,Module module) {
		String uid=CommUtil.null2String(form.get("uid"));
		List<Grab> grabs=new ArrayList<Grab>();
		String checkStyle=CommUtil.null2String(form.get("checkStyle"));
		if(checkStyle.equals("")){checkStyle="checkbox";}
		grabs=grabDAO.getGrabs();
		if(uid.length()>0){
			form.addResult("uid", uid);
		}
		form.addResult("grabList", grabs);
		form.addResult("checkStyle", checkStyle);
		return module.findPage("dialog");
	}
	
	public Page doRename(WebForm form,Module module){
		String id = CommUtil.null2String(form.get("id"));
		String name = CommUtil.null2String(form.get("name"));
		//System.out.print("获取到的名称:"+name);
		Grab grab = grabDAO.getGrabById(id);
		grab.setTitle(name);
		//记录日志
		Logs log=new Logs(user.getUsername()+"编辑采集:"+grab.getTitle());
		logDAO.saveLogs(log);
		grabDAO.updateGrab(grab);
		return null;
	}
	
	public Page doDelete(WebForm form,Module module){
		String id = CommUtil.null2String(form.get("id"));
		if(!id.equals("0")){
			Grab grab = grabDAO.getGrabById(id);
			//记录日志
			Logs log=new Logs(user.getUsername()+"删除采集:"+grab.getTitle());
			logDAO.saveLogs(log);
			grabDAO.delGrab(grab);
		}
		return null;
	}
	
	public Page doShowContent(WebForm form, Module module){
		String id=CommUtil.null2String(form.get("id"));
		String url;
		Grab grab=grabDAO.getGrabById(id);
		if(grab!=null){
			//grab.getListdna_head()==null的时候，url是数据库里第一个地址，
			//如果不为空切长度大于200则为第二个url地址，
			//如果长度小于等于200，则为第二个url列表页中的第一个标题点击进去的内容页的url地址
			if(grab.getListdna_head()==null){
				url = grab.getUrl();
			}else{
				if(grab.getListdna_head().length()<210){
					//url初始值是第二个页面的url
					url = grab.getUrl2();
					Document dom = null;
					Document list = null;
					try {
						//获得页面的document对象
						dom = Jsoup.connect(url).get();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//document对象转化为字符串
					String document = dom.outerHtml();
					document = document.replaceAll("\\r\\n", "");
					document = document.replaceAll("\\r", "");
					document = document.replaceAll("\\n", "");
					document = document.trim();
					//获得列表页的首尾标志位，准备取列表部分代码
					String listdna_head = grab.getListdna_head();
					listdna_head = listdna_head.replaceAll("\\r\\n", "");
					listdna_head = listdna_head.replaceAll("\\r", "");
					listdna_head = listdna_head.replaceAll("\\n", "");
					listdna_head = listdna_head.trim();
					String listdna_foot = grab.getListdna_foot();
					listdna_foot = listdna_foot.replaceAll("\\r\\n", "");
					listdna_foot = listdna_foot.replaceAll("\\r", "");
					listdna_foot = listdna_foot.replaceAll("\\n", "");
					listdna_foot = listdna_foot.trim();
//					int start = document.indexOf(listdna_head);
//					int end = document.indexOf(listdna_foot);
					//准备map容器，将进行相关度计算
					Map<Double,Integer> startMap =new HashMap<Double,Integer>();
					Map<Double,Integer> endMap =new HashMap<Double,Integer>();
					//start、end分别为，列表部分代码在整个document中的起始和结束位置
					int start = 0;
					int end = 0;
					//document对象对应的代码的长度
					int docLength = document.length();
					//首尾标志位代码长度
					int listdna_head_length = listdna_head.length();
					int listdna_foot_length = listdna_foot.length();
					//全文相关度计算，分别把首尾listdna和全文代码做对比，分析出相关度最高的一部分，
					//map的key为double类型，存储相关度值，
					//value为int类型，存储此次相关度计算，进行到全文的哪个位置
					for(int i = 0 ; i < docLength - listdna_head_length ; i++){
						startMap.put(Similarity.likeOf(listdna_head, document.substring(i, i+listdna_head_length-1)), i);
					}
					for(int i = 0 ; i < docLength - listdna_foot_length ; i++){
						endMap.put(Similarity.likeOf(listdna_foot, document.substring(i, i+listdna_foot_length-1)), i);
					}
					start = Similarity.maxValue(startMap);
					end = Similarity.maxValue(endMap);
					//截取列表部分的代码
					String link = document.substring(start + listdna_head_length,end);
					try {
						//获取列表部分代码对应的jsoup对象
						list = Jsoup.parse(link);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//获取所有连接
					Elements links = list.getElementsByTag("a");
					//获取第一个连接
					Element a = links.first();
					//获取这个链接的url,并赋值给url
					url = a.attr("abs:href");
				}else{
					url=grab.getUrl2();
				}
			}
			String content="";
			try {
				Document doc = Jsoup.connect(url).get();
				Element body = doc.select("body").first();
				body.append("<input type=\"hidden\" id=\"grabid\" value=" + id + " name=\"grabid\"/>");
				Elements uls = doc.getElementsByTag("ul");
				Elements ols = doc.getElementsByTag("ol");
				if(uls!=null){
					for(Element ul : uls){
						ul.attr("class", "selected_list");
					}
				}
				if(ols!=null){
					for(Element ol : ols){
						ol.attr("class", "selected_list");
					}
				}
				Elements bases = doc.getElementsByTag("base");
				if(bases!=null&&bases.size()>0){
					doc.select("base").remove();
				}
//				Elements bases = doc.getElementsByTag("base");
//				if(bases!=null&&bases.size()>0){
//					Element base = bases.get(0);
//					base.html("");
//				}
				Element head = doc.getElementsByTag("head").first();
				head.append("<script language='javascript' src='/include/manage/js/jquery.js'></script>");
				head.append("<script language='javascript' src='/include/manage/js/grab.js'></script>");
				head.append("<link rel='stylesheet' href='/include/manage/js/grab_list.css' type='text/css' media='screen' />");
				content=doc.outerHtml();
//				StringBuffer sbscript=new StringBuffer("\n<script language=\"javascript\" src=\"/include/manage/js/jquery.js\"></script>\n");
//				sbscript.append("\n<script language=\"javascript\" src=\"/include/manage/js/grab.js\"></script>\n");
//				sbscript.append("\n<link rel=\"stylesheet\" href=\"/include/manage/js/grab_list.css\" type=\"text/css\" media=\"screen\" />\n ");
//				content+=sbscript.toString();
				if(doc!=null){
					form.addResult("content", content);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			form.addResult("jvalue", content);
		}
		return module.findPage("ajax");
	}
	
	public Page doSetList(WebForm form, Module module){
		String listHtml=CommUtil.null2String(form.get("list"));
		
		return module.findPage("ajax");
	}
	
}
